package com.ruoyi.quartz.util;

import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.common.core.tenant.TenantFrameworkService;
import com.ruoyi.common.utils.tenant.TenantContextHolder;
import org.quartz.JobExecutionContext;
import com.ruoyi.quartz.domain.SysJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 定时任务处理（允许并发执行）
 * 
 * @author ruoyi
 *
 */
public class QuartzJobExecution extends AbstractQuartzJob
{
    private static Logger log = LoggerFactory.getLogger(QuartzJobExecution.class);
    @Override
    protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception
    {
        TenantFrameworkService service = SpringUtil.getBean(TenantFrameworkService.class);
        final List<Long> tenantIds = service.getTenantIds();
        tenantIds.parallelStream().forEach(tenantId ->{
            try {
                TenantContextHolder.setTenantId(tenantId);
                JobInvokeUtil.invokeMethod(sysJob);
            } catch (Exception e) {
                log.error("tenantId="+tenantId+",jobName="+sysJob.getJobName()+" execute fail",e);
            } finally {
                TenantContextHolder.clear();
            }
        });
    }
}
